# 项目配置
PROJECT_NAME := git-ssh-tools
VERSION := v1.0.1
REGISTRY := harbor.k8s.local
IMAGE_NAME := $(REGISTRY)/tools/$(PROJECT_NAME):$(VERSION)
LOCAL_IMAGE_NAME := $(PROJECT_NAME):$(VERSION)

# 认证配置
AUTH := admin:wow1VSlol2

# Docker 配置
DOCKER := sudo docker

.PHONY: help build image tag push search list one test test-image

# 显示帮助信息
help:
	@echo "Usage: make [target]"
	@echo ""
	@echo "Targets:"
	@echo "  help                 显示此帮助信息"
	@echo "  build                构建 Docker 镜像"
	@echo "  tag                  标记镜像为仓库地址"
	@echo "  push                 推送镜像到仓库"
	@echo "  search               查看仓库中的所有镜像"
	@echo "  list                 查看项目的所有镜像标签"
	@echo "  one                  一键构建和推送镜像 (build + tag + push + list)"
	@echo "  test                 运行镜像功能测试"
	@echo "  test-image           测试已构建的镜像功能"

# 构建 Docker 镜像
build:
	$(DOCKER) build -t $(LOCAL_IMAGE_NAME) -f ./Dockerfile .

# 标记镜像
tag:
	$(DOCKER) tag $(LOCAL_IMAGE_NAME) $(IMAGE_NAME)

# 推送镜像到仓库
push:
	$(DOCKER) push $(IMAGE_NAME)

# 查看仓库镜像
search:
	curl -u $(AUTH) -X GET https://$(REGISTRY)/v2/_catalog

# 查看镜像标签
list:
	curl -u $(AUTH) -X GET https://$(REGISTRY)/v2/tools/$(PROJECT_NAME)/tags/list

# 一键构建和推送
one: build tag push list

# 运行镜像功能测试
test: build test-image

# 测试已构建的镜像功能
test-image:
	@echo "测试镜像功能: $(LOCAL_IMAGE_NAME)"
	@echo "1. 验证基础工具是否安装..."
	@$(DOCKER) run --rm $(LOCAL_IMAGE_NAME) git --version >/dev/null 2>&1 && echo "✓ Git 已安装" || (echo "✗ Git 未安装或有问题" && exit 1)
	@$(DOCKER) run --rm $(LOCAL_IMAGE_NAME) ssh -V >/dev/null 2>&1 && echo "✓ SSH 已安装" || (echo "✗ SSH 未安装或有问题" && exit 1)
	@$(DOCKER) run --rm $(LOCAL_IMAGE_NAME) sed --version >/dev/null 2>&1 && echo "✓ Sed 已安装" || (echo "✗ Sed 未安装或有问题" && exit 1)
	@echo "2. 验证用户权限..."
	@$(DOCKER) run --rm $(LOCAL_IMAGE_NAME) whoami | grep -q "tekton" && echo "✓ 使用非root用户运行" || (echo "✗ 用户权限设置有问题" && exit 1)
	@echo "3. 验证工作目录权限..."
	@$(DOCKER) run --rm $(LOCAL_IMAGE_NAME) sh -c "touch /workspace/test-write && rm -f /workspace/test-write" >/dev/null 2>&1 && echo "✓ 工作目录有写入权限" || (echo "✗ 工作目录写入权限有问题" && exit 1)
	@echo "4. 测试sed功能"
	@echo "测试文本" > test-input.txt
	@echo "newTag: old-value" >> test-input.txt
	@$(DOCKER) run --rm -v $(PWD)/test-input.txt:/workspace/test-input.txt $(LOCAL_IMAGE_NAME) sed "s|newTag:.*|newTag: new-value|g" test-input.txt > test-output.txt
	@grep -q "newTag: new-value" test-output.txt && echo "✓ Sed 功能正常" || (echo "✗ Sed 功能有问题" && exit 1)
	@rm -f test-input.txt test-output.txt
	@echo "5. 测试sed -i功能（在容器内部进行）..."
	@$(DOCKER) run --rm $(LOCAL_IMAGE_NAME) sh -c "echo 'newTag: old-value' > test-file.txt && sed -i 's|newTag:.*|newTag: new-value|g' test-file.txt && grep -q 'newTag: new-value' test-file.txt" >/dev/null 2>&1 && echo "✓ Sed -i 功能正常" || (echo "✗ Sed -i 功能有问题" && exit 1)
	@echo "所有测试通过! 镜像功能正常。"

# 默认目标
.DEFAULT_GOAL := help